package org.zjt.platform.demo.config;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import com.alibaba.fastjson.JSONObject;
/**
 * @author <a href="juntao.zhang@qq.com">juntao.zhang</a>
 * @Description:  restController 异常处理
 * @Package org.zjt.platform.demo.config
 * @date 2018/3/12 11:41
 * @see
 */
@ControllerAdvice(annotations = {RestController.class})
@Slf4j
public class RestControllerExceptionHandler extends ResponseEntityExceptionHandler {


	@ExceptionHandler
    @ResponseBody
    ResponseEntity<String> handleException(HttpServletRequest request, Throwable ex) {
        HttpStatus status = getStatus(request);
        String errorMsg=ex.getMessage()==null ? "NullPointerException": ex.getMessage();
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("status", Integer.parseInt(status.toString()));
        map.put("errorMsg", errorMsg);
        log.error("RestController 执行出现异常",ex);
        ResponseEntity<String> entity=new ResponseEntity<String>(JSONObject.toJSONString(map), HttpStatus.valueOf(200));
        return entity;
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }


}
